<?php

namespace addons\fzdc\controller;

use app\admin\model\fzdc\coupon\Coupon as Cp;
use app\admin\model\fzdc\Address;
use app\admin\model\fzdc\coupon\Coupon;
use app\admin\model\fzdc\coupon\Receive;
use app\admin\model\fzdc\point\Goods;
use app\admin\model\fzdc\point\Type;
use app\common\controller\Api;
use app\common\model\ScoreLog;
use app\admin\model\fzdc\order\Point as Po;
use think\Config;
use think\Db;
use think\Request;

class Point extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function __construct(Request $request = null)
    {
        $this->config = get_addon_config("fzdc");
        parent::__construct($request);
    }


    /*
     * 积分明细
     */
    public function detailed()
    {
        $user_id = $this->auth->id;
        $time = $this->request->post('time') ?? "desc";  //页码
        $page = $this->request->post('page') ?? 1;  //页码
        $limit = $this->request->post('limit') ?? 10; //每页显示条数
        $start_time = $this->request->post('start_time') ?? "";
        $end_time = $this->request->post('end_time') ?? "";
        $where = [];
        if (!empty($start_time) && !empty($end_time)) {
            $start_time = strtotime($start_time . " 00:00:00");
            $end_time = strtotime($end_time . " 23:59:59");
            $where['createtime'] = ["between time", [$start_time, $end_time]];
        }
        $data = ScoreLog::where('user_id', $user_id)
            ->where($where)
            ->field("score,memo,before,after,createtime")
            ->order("createtime", $time)
            ->paginate(["page" => $page, "list_rows" => $limit])
            ->each(function ($item) {
                if ($item->before > $item->after) {
                    $item->type = "reduce";
                } else {
                    $item->type = "add";
                }
            });
        $result = array("total" => $data->total(), "rows" => $data->items(), "point" => $this->auth->score);
        $this->success('成功', $result);
    }

    /*
     * 积分规则
     */
    public function rule()
    {
        $this->success('成功', $this->config['rule']);
    }

    /*
     * 兑换记录
     */
    public function take()
    {
        $user_id = $this->auth->id;
        $status = $this->request->post('status');
        $page = $this->request->post('page') ?? 1;  //页码
        $limit = $this->request->post('limit') ?? 10; //每页显示条数
        $time = $this->request->post('time') ?? "";
        $where = [];
        if ($status) {
            $where['status'] = ["=", $status];
        }
        if (!empty($time)) {
            $start_time = strtotime($time . " 00:00:00");
            $end_time = strtotime($time . " 23:59:59");
            $where['createtime'] = ["between time", [$start_time, $end_time]];
        }
        $data = Po::where("user_id", $user_id)
            ->where($where)
            ->order("id", "desc")
            ->field("id,order_no,goods_id,coupon_id,status,goods_count,order_amount_total,pay_time,delivery_time,courier,numbers")
            ->paginate(["page" => $page, "list_rows" => $limit])
            ->each(function ($item) {
                if ($item->coupon_id != 0) {
                    $item->goods_name = Coupon::where("id", $item->coupon_id)->value("title");
                    $image = Coupon::where("id", $item->coupon_id)->value("image");
                } else {
                    $item->goods_name = Goods::where("id", $item->goods_id)->value("title");
                    $image = Goods::where("id", $item->goods_id)->value("thumbnail");
                }
                $image = cdnurl($image, true);
                $item->image = $image;
            });

        $result = array("total" => $data->total(), "rows" => $data->items());
        $this->success('返回成功', $result);
    }

    /*
     * 兑换记录详情
     */
    public function take_detail()
    {
        $user_id = $this->auth->id;
        $id = $this->request->post('id');
        if (!$id) {
            $this->error("缺少id");
        }
        $res = Po::get($id);
        if (!$res) {
            $this->error("不存在此数据");
        }
        $data = Po::where("user_id", $user_id)
            ->where(["id" => $id])
            ->field("id,order_no,goods_id,coupon_id,status,goods_count,order_amount_total,pay_time,remark")
            ->find();
        if (!$data) {
            $this->error("无此数据");
        }

        if ($data['coupon_id'] != 0) {
            $data['goods_name'] = Coupon::where("id", $data['coupon_id'])->value("title");
            $image = Coupon::where("id", $data['coupon_id'])->value("image");
        } else {
            $data['goods_name'] = Goods::where("id", $data['goods_id'])->value("title");
            $image = (new \app\admin\model\fzdc\point\Goods)->where("id", $data['goods_id'])->value("thumbnail");
        }
        $image = cdnurl($image, true);
        $data['image'] = $image;

        $this->success('返回成功', $data);
    }

    /*
     * 积分商品分类
     */
    public function type()
    {
        $data = Type::where("state", 1)->where("deletetime", null)->order("weigh", "desc")->field("id,name")->select();
        $this->success('成功', $data);
    }

    /*
     * 商品列表
     */
    public function list()
    {
        $type = $this->request->post('type');
        $page = $this->request->post('page') ?? 1;  //页码
        $limit = $this->request->post('limit') ?? 10; //每页显示条数
        $where = '';
        if ($type) {
            $where = array('type_id' => $type);
        }
        $data = Goods::where('state', 1)
            ->where($where)
            ->where("deletetime", null)
            ->field("id,coupon_id,title,price,stock,thumbnail")
            ->paginate(["page" => $page, "list_rows" => $limit])
            ->each(function ($item) {
                if ($item->coupon_id != 0) {
                    $item->title = Coupon::get($item->coupon_id)['title'];
                }
            });
        $result = array("total" => $data->total(), "rows" => $data->items());
        $this->success('返回成功', $result);
    }

    /*
     * 商品详情
     */
    public function detail()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error("缺少积分商品id");
        }
        $data = Goods::where('state', 1)
            ->where('id', $id)
            ->field("id,title,coupon_id,description,content,need,images,price,line_price,stock")
            ->find();
        if ($data['coupon_id'] != 0) {
            $data['title'] = Coupon::get($data['coupon_id'])['title'];
        }
        $images = explode(',', $data['images']);
        foreach ($images as &$v) {
            $v = cdnurl($v, true);
        }
        $data['images'] = $images;
        $this->success('返回成功', $data);
    }

    /*
     * 兑换积分商品
     */
    public function exchange()
    {
        $user_id = $this->auth->id;
        $id = $this->request->post('id');
        $address_id = $this->request->post('address_id');
        if (!$id) {
            $this->error("缺少积分商品id");
        }
        $goodsCount = 1;
        $score = $this->auth->score;//用户积分
        //查询商品
        $goods = Goods::where("id", $id)->field("id,title,coupon_id,price,stock,daily")->find();

        if ($goods['coupon_id'] == 0) {
            //周边或者其他商品 需要收货地址
            if (!$address_id) {
                $this->error("缺少收货地址");
            }
            //判断收货地址是否存在
            $address = Address::get($address_id);
            if (!$address) {
                $this->error("收货地址不存在");
            }
        }

        //判断库存
        if ($goods['stock'] < 1) {
            $this->error("库存不足");
        }

//        //判断日限购
//        $count = Po::where(["user_id" => $user_id, 'goods_id' => $id])
//            ->where("pay_time", ">=", strtotime(date('Y-m-d ') . '00:00:00'))
//            ->where("pay_time", "<=", strtotime(date('Y-m-d ') . '23:59:59'))
//            ->sum("goods_count");
//        if (bcadd($count, $goodsCount) > $goods['daily']) {
//            $this->error("所购买数量超过今日剩余购买数量,今日剩余购买数量:" . bcsub($goods['daily'], bcadd($count, $goodsCount)));
//        }

        //判断用户积分是否充足
        if ($score > 0) {
            $goodsTotal = bcmul($goods['price'], $goodsCount, 2);
            if ($score < $goodsTotal) {
                $this->error("用户可用积分不足");
            }
        } else {
            $this->error("用户可用积分不足");
        }
        $price = $goods['price'];
        $goods_prices = bcmul($goods['price'], $goodsCount);
        $orderNo = fzdc_orderNo($user_id);
        //生成订单
        $data = [
            "order_no" => $orderNo,
            "user_id" => $user_id,
            "goods_id" => $id,
            "goods_count" => $goodsCount,
            "goods_price" => $price,
            "goods_prices" => $goods_prices,
            "order_amount_total" => $goods_prices,
            "pay_time" => time(),
        ];
        if ($goods['coupon_id'] == 0) {
            //普通积分订单
            $data['address_id'] = $address_id;
            $data['status'] = 1;//待发货
        } else {
            //优惠券积分订单
            $data['coupon_id'] = $goods['coupon_id'];
            $data['status'] = 3;//已完成
        }
        //数据入库
        Db::startTrans();
        try {
            //插入订单表
            Po::create($data);
            if ($goods['coupon_id'] != 0) {
                $coupon = Cp::get($goods['coupon_id']);
                //添加优惠券领取记录
                Receive::create([
                    "user_id" => $user_id,
                    "coupon_id" => $goods['coupon_id'],
                    "money" => $coupon['used_amount'],
                    "create_time" => time(),
                    "state" => 0,
                ]);
            }
            //更新积分明细
            $user = \app\admin\model\User::find($user_id);
            $before = $user->score;
            $after = $user->score - $goods_prices;
            $level = $this->nowlevel($after);
            //更新会员信息
            \app\admin\model\User::where(["id" => $user_id])->update([
                "score" => $after,
                "level" => $level
            ]);
            //更新商品库存
            Goods::where("id", $id)->setDec("stock", $goodsCount);
//            $user->save(['score' => $after, 'level' => $level]);
            //写入日志
            ScoreLog::create(['user_id' => $user_id, 'score' => $goods_prices, 'before' => $before, 'after' => $after, 'memo' => "购买" . $goods['title'] . "扣除" . $goods_prices . "积分"]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error("数据录入失败：" . $e->getMessage());
        }
        $this->success('成功', ["orderNo" => $orderNo]);
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public function nowlevel($score = 0)
    {
        $lv = $this->config['upgrade'];
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }

}
